package com.no1ikun.service;

import com.no1ikun.bean.Teacher;
import com.no1ikun.util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;

public class TeacherServiceImpl implements TeacherService{
    public static String Tid;

    public TeacherServiceImpl() {
        Tid=generateTid();
    }

    public static void main(String[] args) {
        TeacherService t=new TeacherServiceImpl();
        Teacher teacher=t.login_adm("T0001 ","T000001");
        System.out.println(teacher.toString());
        System.out.println(TeacherServiceImpl.Tid);

    }
    @Override
    public Teacher login_adm(String tid, String password) {
        //去数据库查询是否有这个学生
        String sql = "select * from Teacher where tid=?";
        //使用手机号码或者学号登入
        ResultSet rs = JDBCUtil.executeQuery(sql, tid);
        //创建一个学老师对象
        Teacher teacher = null;
        try {
            if (rs.next()) {

                String sno = rs.getString("tid");
                String spwd = rs.getString("tpwd");
                String sname = rs.getString("tname");
                //实例化学生对象
                teacher = new Teacher(sno,spwd,sname);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //判断数据库是否查询到学生
        if (teacher != null) {
            //判断密码是否正确
            if (teacher.getTpwd().equals(password)) {
                //说明用户是正确的
                return teacher;
            }
        }
        return null;
    }

    @Override
    public int insertTeacher(String name, String pwd) {
        String sql = "INSERT INTO Teacher(tid,tname,tpwd,dname) VALUES (?,?,?,?);";
        System.out.println(Tid+"---"+name+"---"+pwd);
        int i = JDBCUtil.executeUpdate(sql, Tid,name,pwd,"暂未分配");
        return i;
    }

    public String generateTid(){
        String selSql = "select top 1  tid from Teacher order by tid DESC";
        System.out.println(selSql);
        String newNumber="T0001";
        ResultSet rs = JDBCUtil.executeQuery(selSql);
        try {
            if (rs.next()) {
                //学号构成 年+系编号+班级号+学号
                //获取number
                String number = rs.getString("tid").trim();
                //班级号 应该是枚举类型

                String substring = number.substring(number.length()-2);
                int i=Integer.parseInt(substring)+1;
                newNumber="T00"+((i+"").length()>=2?i:"0"+i);

            }

        } catch (Exception e) {

        }
        //获取老师的id
        return newNumber;

    }
}
